# Create your views here.
from django import template
from django.http import HttpResponse
from Common.decorators import check_body
from Common.decorators import check_param
from Common.decorators import check_token
from Common.decorators import method
from Common.logger import app_log
from Common.response import resp
from Admin.models import Tag
from EducationContent.models import Hospital
from EducationContent.models import EducationFeeds
from EducationContent.models import EducationCategory
from EducationContent.models import CardAttributes
import json
from datetime import datetime
from django.shortcuts import render
from django.db.models import Max
from django.db.models import Q
import re


@check_token()
@check_param(['content_id', 'language'])
@method(["GET"])
def content_details(request):
    try:
        content_id = request.GET.get('content_id')
        language = request.GET.get('language')
        record = EducationFeeds.objects.filter(id=content_id).first()
        if not record:
            return resp(4001)
        data = record.educationFeeds_details_to_json()
        hospital_name = Hospital.objects.filter(id=data['hospital_id']).first()
        if not hospital_name:
            return resp(4001)

        data['hospital_name'] = hospital_name.hospital_name

        # category info :
        category_array = EducationCategory.get_parent_array(data['category_id'], data['hospital_id'])
        data['category_array'] = category_array

        # append body array
        if language == 'SP':
            data['title'] = record.title_SP
            data['summary_1'] = record.summary_1_SP
            data['summary_2'] = record.summary_2_SP
            data['title_media_url'] = record.title_media_url_SP
            data['page_info'] = record.page_info_SP

        tags_ret = []
        tags = []
        if data['tags']:
            tags = data["tags"].split(',')
        if tags:
            for it in tags:
                record = Tag.objects.filter(id=str(it)).first()
                if record:
                    tag = record.tag_tojson()
                    tags_ret.append(tag)
        data['tags'] = tags_ret

        data['language'] = language if language in ['EN', 'SP'] else 'EN'
        return resp(0, data=data)

    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


@check_token()
@check_param(['category_id', 'hospital_id'])
def content_list(request):
    try:
        data = {}
        category_id = request.GET.get('category_id')
        hospital_id = request.GET.get('hospital_id')
        category = EducationCategory.objects.filter(cid=category_id, hospital_id=hospital_id).first()
        if not category:
            return resp(4001)
        content_list = EducationFeeds.objects.filter(
            hospital_id=hospital_id, category_id=category_id, is_delete=0
        ).all()
        if not content_list or len(content_list) == 0:
            return resp(4001)
        list = []
        for it in content_list:
            relates = []
            if it.related_content_1: relates.append(it.related_content_1)
            if it.related_content_2: relates.append(it.related_content_2)
            if it.related_content_3: relates.append(it.related_content_3)
            if it.related_content_4: relates.append(it.related_content_4)
            feed_json = it.educationFeeds_to_json()
            if len(relates) > 0:
                related_content = EducationFeeds.get_related_content(list=relates)
                feed_json['related_content'] = related_content
            list.append(feed_json)

        data["content_list"] = list

        return resp(0, data)
    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


@check_token()
@check_body(['upload_to', 'title', 'title_media_type', 'source'])
def content_create(request):
    try:
        date = datetime.utcnow()
        post_param = json.loads(request.body)

        # save content to dabe
        def save_content(hospital_id, category_id, all_hospital=False):
            current_max_order = EducationFeeds.objects.filter(
                hospital_id=hospital_id,
                category_id=category_id
            ).all().aggregate(Max('content_order'))['content_order__max']
            content_order = current_max_order + 1 if current_max_order else 1
            record = EducationFeeds(
                hospital_id=hospital_id,
                category_id=category_id,
                title=post_param['title'],
                title_SP=post_param['title'],
                summary_1=post_param['summary_1'] if 'summary_1' in post_param else None,
                summary_2=post_param['summary_2'] if 'summary_2' in post_param else None,
                summary_1_SP=post_param['summary_1'] if 'summary_1' in post_param else None,
                summary_2_SP=post_param['summary_2'] if 'summary_2' in post_param else None,
                source=post_param['source'],
                tags=post_param['tags'] if 'tags' in post_param else None,
                title_media_type=post_param['title_media_type'],
                title_media_url=post_param['title_media_url'],
                title_media_url_SP=post_param['title_media_url'],
                content_order=content_order,
                related_content_1=post_param['related_content_1'] if 'related_content_1' in post_param else None,
                related_content_2=post_param['related_content_2'] if 'related_content_2' in post_param else None,
                related_content_3=post_param['related_content_3'] if 'related_content_3' in post_param else None,
                related_content_4=post_param['related_content_4'] if 'related_content_4' in post_param else None,
                time_of_delivery_week=0,
                time_of_delivery_day=0,
                time_of_delivery_hour=0,
                created_at=date,
                updated_at=date
            )

            if post_param['title_media_url']:
                record.page_info = post_param["page_info"]
                record.page_info_SP = post_param["page_info"]
            else:
                page_content = post_param["page_info"]
                img_exist = re.findall('<figure class="image">(.*?)</figure>', page_content)
                if img_exist:
                    image_content = re.search('<figure class="image">(.*?)</figure>', page_content)
                    real_content = page_content.replace(image_content.group(0), "")
                    record.page_info = real_content
                    record.page_info_SP = real_content
                    img_path = re.findall('<figure class="image">(.*?)</figure>', page_content)[0].split('"')[-2]
                    record.title_media_url = img_path
                else:
                    record.page_info = page_content
                    record.page_info_SP = page_content

            record.save()

        ret = {}
        success = []
        failures = []

        if len(post_param['upload_to']['hospital_list']) < 1:
            return resp(4009)

        if post_param['upload_to']['all_hospital'] == 1:
            all_hospital_id = list(Hospital.objects.values_list("id", flat=True).all())
            hospital_list = post_param['upload_to']['hospital_list']
            category_id = hospital_list[0]['category_id']

            for hospital_id in all_hospital_id:
                records = EducationCategory.objects.filter(cid=category_id, hospital_id=hospital_id).all()
                if not records:
                    category_id = 'root'
                save_content(hospital_id, category_id, all_hospital=True)
                inserted = {'hospital_id': hospital_id, 'category_id': category_id}
                success.append(inserted)
                ret['success'] = success
                ret['failure'] = failures
        else:
            hospital_list = post_param['upload_to']['hospital_list']
            for hospital in hospital_list:
                hospital_id = hospital['hospital_id']
                category_id = hospital['category_id']
                records = EducationCategory.objects.filter(cid=category_id, hospital_id=hospital_id).all()
                if not records:
                    not_inserted = {'hospital_id': hospital_id, 'category_id': category_id}
                    failures.append(not_inserted)
                    continue
                else:
                    inserted = {'hospital_id': hospital_id, 'category_id': category_id}
                    success.append(inserted)
                save_content(hospital_id, category_id, all_hospital=False)
            ret['create_success'] = success
            ret['create_failure'] = failures
        return resp(0, ret)
    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


# @check_token()
@check_body(['id', 'title', 'title_media_type', 'source', 'language'])
def content_update(request):
    try:
        post_param = json.loads(request.body)
        hospital_id = post_param['hospital_id']
        category_id = post_param['category_id']
        source = post_param['source']
        content_id = post_param['id']
        if type(source) is not int:
            return resp(4011)
        language = post_param['language'] if 'language' in post_param else 'EN'

        def save_content(content_id, hospital_id, other_hospital=False):
            date = datetime.utcnow()
            success = False
            record_current = EducationFeeds.objects.get(id=content_id)
            if not record_current: return resp(4001)
            if other_hospital:
                pass
            else:
                record_current.hospital_id = hospital_id
                record_current.category_id = category_id

            if language == 'SP':
                record_current.title_SP = post_param['title']
                record_current.summary_1_SP = post_param['summary_1'] if 'summary_1' in post_param else None
                record_current.summary_2_SP = post_param['summary_2'] if 'summary_2' in post_param else None
                record_current.title_media_url_SP = post_param['title_media_url']
            elif language == 'EN':
                record_current.title = post_param['title']
                record_current.summary_1 = post_param['summary_1'] if 'summary_1' in post_param else None
                record_current.summary_2 = post_param['summary_2'] if 'summary_2' in post_param else None
                record_current.title_media_url = post_param['title_media_url']

            record_current.title_media_type = post_param['title_media_type']
            record_current.source = source
            record_current.tags = post_param['tags'] if 'tags' in post_param else None

            record_current.related_content_1 = post_param[
                'related_content_1'] if 'related_content_1' in post_param else None
            record_current.related_content_2 = post_param[
                'related_content_2'] if 'related_content_2' in post_param else None
            record_current.related_content_3 = post_param[
                'related_content_3'] if 'related_content_3' in post_param else None
            record_current.related_content_4 = post_param[
                'related_content_4'] if 'related_content_4' in post_param else None
            record_current.updated_at = date

            if post_param['title_media_url']:
                if language == 'EN':
                    record_current.page_info = post_param["page_info"]
                elif language == 'SP':
                    record_current.page_info_SP = post_param["page_info"]
            else:
                page_content = post_param["page_info"]
                img_exist = re.findall('<figure class="image">(.*?)</figure>', page_content)
                if img_exist:
                    image_content = re.search('<figure class="image">(.*?)</figure>', page_content)
                    real_content = page_content.replace(image_content.group(0), "")
                    img_path = re.findall('<figure class="image">(.*?)</figure>', page_content)[0].split('"')[-2]
                    # record_current.page_info = real_content
                    # record_current.title_media_url = img_path
                    if language == 'EN':
                        record_current.page_info = real_content
                        record_current.title_media_url = img_path
                    elif language == 'SP':
                        record_current.page_info_SP = real_content
                        record_current.title_media_url_SP = img_path
                else:
                    if language == 'EN':
                        record_current.page_info = page_content
                    elif language == 'SP':
                        record_current.page_info_SP = page_content

            record_current.save()
            success = True
            return {"status": success, 'content_id': content_id, 'hospital_id': hospital_id}

        ret = []
        r = save_content(content_id=content_id, hospital_id=hospital_id)
        ret.append(r)
        if 'other_hospital' in post_param and len(post_param['other_hospital']) > 0:
            for it in post_param['other_hospital']:
                content_id = it['content']['id']
                hospital_id = it['hospital']['id']
                r = save_content(content_id=content_id, hospital_id=hospital_id, other_hospital=True)
                ret.append(r)

        return resp(0, ret)
    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


@check_token()
@check_body(['title', 'language', 'current_hospital_id'])
def check_other_hospital(request):
    try:
        ret = []
        post_param = json.loads(request.body)
        if post_param['title'] == 'SP':
            other_hospitals = EducationFeeds.objects.filter(title_SP=post_param['title'], is_delete=False).all()
        else:
            other_hospitals = EducationFeeds.objects.filter(title=post_param['title'], is_delete=False).all()
        for content in other_hospitals:
            r = {}
            hospital_info = Hospital.objects.filter(id=content.hospital_id, is_delete=False).first()
            if hospital_info:
                if hospital_info.id == post_param['current_hospital_id']:
                    continue
                r['hospital'] = hospital_info.hospital_to_json()
                r['content'] = {"id": content.id,
                                "title": content.title_SP if post_param['title'] == 'SP' else content.title}
                ret.append(r)
        return resp(0, ret)

    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


# @check_token()
@check_body(['title', 'title_type', 'source'])
def content_same_count(request):
    try:
        ret = {}
        date = datetime.utcnow()
        post_param = json.loads(request.body)
        hospital_id = post_param['hospital_id']
        category_id = post_param['category_id']
        record_current = EducationFeeds.objects.get(id=post_param['id'])
        records = EducationFeeds.objects.get(title=record_current.title, is_delete=0).all()

        ret['count'] = len(records)
        return resp(0, ret)

    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


@method(['POST'])
@check_token()
@check_body(['hospital_id', 'content_id', 'category_id', 'content_list'])
def content_move(request):
    # todo change content order
    try:
        date = datetime.utcnow()
        body_json = json.loads(request.body)
        hospital_id = body_json['hospital_id']
        content_id = body_json['content_id']
        category_id = body_json['category_id']
        content_list = body_json['content_list']

        # check record whether correct
        record = EducationFeeds.objects.filter(id=content_id).first()
        if not record:
            return resp(4001)

        records = list(EducationFeeds.objects.values_list("id", flat=True).filter(
            category_id=category_id, hospital_id=hospital_id, is_delete=0
        ).all())
        if record.category_id == category_id:
            pass
        else:
            records.append(content_id)

        if len(content_list) != len(records):
            return resp(4002, {})

        for it in content_list:
            if it not in records:
                return resp(4002, {})

        records_old = list(EducationFeeds.objects.values_list("id", flat=True).filter(
            category_id=record.category_id, hospital_id=record.hospital_id, is_delete=0
        ).all())
        for i in range(len(records_old)):
            EducationFeeds.objects.filter(id=records_old[i]).update(
                content_order=i + 1, updated_at=date
            )

        record.category_id = category_id
        record.save()
        for i in range(len(records)):
            EducationFeeds.objects.filter(id=content_list[i]).update(
                content_order=i + 1, updated_at=date
            )
        return resp(0, {})

    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


@method(['POST'])
@check_token()
@check_body(['category_id', 'hospital_id_from', 'hospital_id_to', 'category_to', 'level_to', 'order'])
def category_move(request):
    # todo change content order
    try:
        date = datetime.utcnow()
        body_json = json.loads(request.body)

        category_id = body_json['category_id']
        hospital_id_from = body_json['hospital_id_from']
        hospital_id_to = body_json['hospital_id_to']
        category_to = body_json['category_to']
        level_to = body_json['level_to']

        order = body_json['order']

        # check record
        records = EducationCategory.objects.filter(cid=category_id, hospital_id=hospital_id_from).first()
        if category_to == 'root':
            pass
        else:
            records_to = EducationCategory.objects.filter(cid=category_to, hospital_id=hospital_id_to).first()
            if not records_to:
                return resp(4001, {"category_id": category_to, 'hospital_id': hospital_id_to})

        if not records:
            return resp(4001, {"category_id": category_id, 'hospital_id': hospital_id_from})

        to_title_list = EducationCategory.objects.filter(hospital_id=hospital_id_to, parent_id=category_to).values(
            'title').all()
        if records.title in to_title_list:
            return resp(4003)
        category_from = records.parent_id

        records.parent_id = category_to
        records.hospital_id = hospital_id_to
        records.level = level_to
        records.order_id = order
        records.updated_at = date

        records.save()

        #
        if category_to == category_from:
            to_list = EducationCategory.objects.filter(
                hospital_id=hospital_id_to, parent_id=category_to
            ).order_by('order_id', '-updated_at').all()
            app_log.info(to_list)
            for i in range(len(to_list)):
                category = to_list[i]
                category.order_id = i + 1
                category.save()

        else:
            from_list = EducationCategory.objects.filter(
                hospital_id=hospital_id_from, parent_id=category_from
            ).order_by('order_id', '-updated_at').all()
            for i in range(len(from_list)):
                category = from_list[i]
                category.order_id = i + 1
                category.save()

            to_list = EducationCategory.objects.filter(
                hospital_id=hospital_id_to, parent_id=category_to
            ).order_by('order_id', '-updated_at').all()
            app_log.info(to_list)
            for i in range(len(to_list)):
                category = to_list[i]
                category.order_id = i + 1
                category.save()

        return resp(0)
    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


@check_token()
def content_delete(request):
    try:
        body_json = json.loads(request.body)
        content_id = body_json['content_id']
        record = EducationFeeds.objects.filter(id=content_id).first()
        if record:
            record.delete()
        else:
            return resp(4001)

        return resp(0)

    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


# @check_token()
def content_html(request, content_id):
    try:
        language = request.GET.get('language')
        record = EducationFeeds.objects.filter(id=content_id).first()
        if not record:
            return resp(4001)
        content_info = record.educationFeeds_details_to_json()
        return render(request, "content.html", {'content_info': content_info, 'language': language})
    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


@check_token()
def relate_content_info(request):
    try:
        post_param = json.loads(request.body)

        ret = []
        relate_content = post_param['relate_contents']

        for it in relate_content:
            content_info = {}
            relate_record = EducationFeeds.objects.filter(id=it).first()
            if relate_record:
                title = relate_record.title
                title_type = relate_record.title_type
                tittle_type_url = relate_record.title_image if title_type == "image" else relate_record.title_video
                content_info['tittle'] = title
                content_info['media_type'] = title_type
                content_info['media_url'] = tittle_type_url
                ret.append(content_info)

        return resp(0, ret)

    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


@method(['GET'])
@check_token()
@check_param(['category_id', 'hospital_id'])
def category_detail(request):
    try:
        ret = {}
        category_id = request.GET.get('category_id')
        hospital_id = request.GET.get('hospital_id')
        content_list = []
        category_list = []
        category_records = EducationCategory.objects.filter(parent_id=category_id, hospital_id=hospital_id).all()
        content_records = EducationFeeds.objects.filter(category_id=category_id, hospital_id=hospital_id,
                                                        is_delete=0).all()
        for category in category_records:
            json_d = category.category_to_json()
            cid = json_d['cid']
            json_d.pop("cid")
            json_d['id'] = cid
            json_d['type'] = 0
            category_list.append(json_d)
        for content in content_records:
            json_d = content.educationFeeds_to_json()
            json_d['type'] = 1
            content_list.append(json_d)
        ret['category_list'] = category_list
        ret['content_list'] = content_list

        return resp(0, ret)

    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


@method(['GET'])
@check_token()
@check_param(['category_id', 'hospital_id'])
def super_category_detail(request):
    try:
        ret = {}
        category_id = request.GET.get('category_id')
        hospital_id = request.GET.get('hospital_id')
        # category info :
        category_array = EducationCategory.get_parent_array(category_id, hospital_id)
        hospital_record = Hospital.objects.filter(is_delete=False, id=hospital_id).first()
        hospital_json = {
            "hospital_name": hospital_record.hospital_name,
            "hospital_id": hospital_record.id
        }
        ret['hospital_detail'] = hospital_json
        ret['category_array'] = category_array
        return resp(0, ret)

    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


def search(request):
    try:
        title = request.GET.get('title')
        summary_1 = request.GET.get('summary_1')
        summary_2 = request.GET.get('summary_2')
        page_info = request.GET.get('page_info')
        user_id = request.GET.get('user_id')

        content = []
        records = EducationFeeds.objects.filter(
            Q(title__contains=title) or Q(summary_1__contains=summary_1) or
            Q(summary_2__contains=summary_2) or Q(page_info_SP__contains=page_info)
        ).all()
        for feed in records:
            # http://127.0.0.1:9000/api/admin/education_content/content/68
            ret = {
                "id": feed.id, "card_title": feed.title, "summary_1": feed.summary_1, "summary_2": feed.summary_2,
                "content_url": '/api/admin/education_content/content/' + str(feed.id)
            }
            if feed.title_media_url:
                ret['card_media'] = feed.title_media_url

            if CardAttributes.objects.filter(
                    feed_id=feed.id, user_id=user_id, card_attribute='bookmark').first():
                ret['bookmarked'] = True
            else:
                ret['bookmarked'] = False

            content.append(ret)

        return resp(0, {"data": content})
    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))
